const {getRoleList, updateRole} = require("../controller/role");
const {getAuthorityList} = require("../controller/authority");
const Response = require('../common/Response')
const router = require('koa-router')()

router.prefix('/api/role')

// 获取角色与权限列表
router.get('/list', async (context, next) => {
  const roles = await getRoleList()
  let rights = await getAuthorityList()
  // 过滤角色已有的权限
  roles.forEach(item => {
    item.children = rights.filter(ele => ele.role_id === item.id && ele.level === 0 && ele.isown === 0);
    item.children.forEach(sub => {
      sub.children = rights.filter(thr => thr.pid === sub.id && thr.level === 1 && thr.isown === 0);
    })
  })
  context.body = Response.success(roles)
})
// 仅获取角色信息
router.get('/list/only', async (context, next) => {
  const rows = await getRoleList()
  context.body = Response.success(rows)
})
// 修改角色描述信息
router.post('/update', async (context, next) => {
  const val = await updateRole(context.request.body)
  if (val) {
    context.body = Response.success(`修改${context.request.body.role_name}角色描述成功`)
  } else {
    context.body = Response.failure(`修改${context.request.body.role_name}角色描述失败`)
  }
})

module.exports = router
